package engine.services.impl;

import javax.mail.internet.MimeMessage;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.security.util.InMemoryResource;

import engine.content.ContentTypes;
import engine.content.FileContent;
import engine.content.IContent;
import engine.content.InMemoryContent;
import engine.mail.IMailMessage;
import engine.mail.MimeMessageWrapper;
import engine.services.IMailSender;

@SuppressWarnings("rawtypes")
public class SpringMailSenderImpl extends JavaMailSenderImpl implements IMailSender {


	@Override
	public IMailMessage createMessage() {
		MimeMessage mm = createMimeMessage();
		return new MimeMessageWrapper(mm);
	}

	@Override
	public void send(IMailMessage mm) throws Exception {
		
		MimeMessage message = (MimeMessage)mm.getMessage();
		message.saveChanges();
		super.send(message);
	}


	@Override
	public void addAttachment(IContent content, Resource res, IMailMessage message, String fileName, String fileId)
			throws Exception {
		MimeMessageWrapper mmw = (MimeMessageWrapper)message;
		MimeMessageHelper helper = new MimeMessageHelper(mmw.getMessage(), true);
		mmw.setMimeMessageHelper(helper);
		if (res instanceof InMemoryResource) {
			helper.addAttachment(fileName, res, content.getContentType());
		} else {
			helper.addAttachment(fileName, ((FileContent)content).getContent());						
		}
		helper.addInline(fileId, res, content.getContentType());	
	}
}
